package com.smyh.UIM;

import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.smyh.adapter.MsgAdapter;
import com.smyh.bean.Msg;
import com.smyh.cache.PreferenceCommon;
import com.smyh.cache.PreferenceSocketInfo;
import com.smyh.common.MinaClientThread;
import com.smyh.util.HexStrUtil;

import org.apache.mina.core.buffer.IoBuffer;

import java.util.ArrayList;
import java.util.List;

public class WifiSetActivity extends AppCompatActivity {

    private EditText editText_ip_01, editText_ip_02, editText_ip_03, editText_ip_04, editText_port;
    private EditText cmd_msg_text;
    private TextView connect_state_msg;
    private Button cmd_send_btn;
    private ToggleButton btn_connect;
    private Handler handler;
    public static List<Msg> msgList = new ArrayList<>();
    public static MsgAdapter adapter ;
    /**
     * wifi连接是否自动
     */
    public static boolean autoConnected = false;
    static int connects = 0;

    static boolean isRefresh = false;
    static ListView msgListView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wifi_set_layout);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 0: {
                        if(autoConnected){
                            btn_connect.setEnabled(false);
                            btn_connect.setChecked(false);
                            btn_connect.setText("连接中");
                            connect_state_msg.setText("......");
                            if(MinaClientThread.isCommplete){
                                new Thread(new MinaClientThread()).start();
                            }

                            if(connects++ > 30){
                                autoConnected = false;
                                connects = 0;
                                btn_connect.setEnabled(true);
                            }

                        }else{
                            btn_connect.setEnabled(true);
                            btn_connect.setChecked(false);
                            btn_connect.setText("连接");
                            connect_state_msg.setText("未连接...");
                        }
                        break;
                    }
                    case 1: {
                        btn_connect.setEnabled(true);
                        btn_connect.setChecked(true);
                        btn_connect.setText("断开");
                        connect_state_msg.setText("连接成功...");

                        break;
                    }
                    default:
                        break;
                }
            }
        };
        initView();
        initData();
        initEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isRefresh = true;
        refreshWifiSetList();
        Log.i("wifiSetActivity","onResume");
    }

    @Override
    protected void onStop() {
        super.onStop();
        isRefresh = false;
        Log.i("wifiSetActivity","opStop");
    }

    private void initEvent() {
        editText_ip_01.setOnKeyListener(socketParamKeyListener);
        editText_ip_02.setOnKeyListener(socketParamKeyListener);
        editText_ip_03.setOnKeyListener(socketParamKeyListener);
        editText_ip_04.setOnKeyListener(socketParamKeyListener);

        editText_ip_01.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_1,192));
        editText_ip_02.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_2,168));
        editText_ip_03.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_3,1));
        editText_ip_04.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_IP_4,1));

        editText_port.setOnKeyListener(socketParamKeyListener);
        editText_port.setText("" + PreferenceCommon.sPreferences.getInt(PreferenceSocketInfo.SERVER_PORT,9911));

        btn_connect.setOnClickListener(btn_click_listener);
        cmd_send_btn.setOnClickListener(btn_click_listener);
        msgListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(WifiSetActivity.this, "长按复制报文内容！", Toast.LENGTH_SHORT).show();
            }
        });

        final String[] PK = {"复制","全部删除","删除当前数据"};

        msgListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(final AdapterView<?> parent, View view, final int position, long id) {
                new AlertDialog.Builder(WifiSetActivity.this)
                        .setTitle("进行的操作")
                        .setItems(PK,
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        switch (which){
                                            case 0:{

                                                ClipboardManager cmb = (ClipboardManager) WifiSetActivity.this.getSystemService(Context.CLIPBOARD_SERVICE);
                                                cmb.setText(msgList.get(position).getContent().trim());
                                                break;
                                            }
                                            case 1:{
                                                msgList.clear();
                                                refreshWifiSetList();
                                                break;
                                            }
                                            case 2:{
                                                msgList.remove(position);
                                                refreshWifiSetList();
                                                break;
                                            }
                                        }

                                        Toast.makeText( WifiSetActivity.this, PK[which], Toast.LENGTH_SHORT).show();
                                    }
                                })
                        .setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        // TODO Auto-generated method stub

                                    }
                                }).show();
                return true;
            }

        });

    }

    static Handler handler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            adapter.notifyDataSetChanged();
            msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        }
    };
    public static void refreshWifiSetList(){
        if(isRefresh){
            handler1.obtainMessage().sendToTarget();
        }
    }

    private void initData() {
    }

    private void initView() {
        editText_ip_01 = (EditText) findViewById(R.id.editText_ip1);
        editText_ip_02 = (EditText) findViewById(R.id.editText_ip2);
        editText_ip_03 = (EditText) findViewById(R.id.editText_ip3);
        editText_ip_04 = (EditText) findViewById(R.id.editText_ip4);

        editText_port = (EditText) findViewById(R.id.editText_port);

        cmd_msg_text = (EditText) findViewById(R.id.cmd_msg_text);
        cmd_send_btn = (Button) findViewById(R.id.cmd_send_btn);
        btn_connect = (ToggleButton) findViewById(R.id.btn_connect);
        connect_state_msg = (TextView) findViewById(R.id.connect_state_msg);
        msgListView = (ListView) findViewById(R.id.list_view);
        adapter = new MsgAdapter(WifiSetActivity.this, R.layout.msg_item, msgList);
        msgListView.setAdapter(adapter);
        msgListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);

        /**
         * 刷新界面组件状态：
         */
        new Thread(new Runnable() {
            @Override
            public void run () {
                while (true) {
                    if (MinaClientThread.session == null || MinaClientThread.session.isClosing()) {
                        handler.obtainMessage(0).sendToTarget();
                    } else {
                        handler.obtainMessage(1).sendToTarget();
                    }
                    try {
                        Thread.sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }).start();
    }

    /**
     *
     */

    public View.OnKeyListener socketParamKeyListener = new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            Log.i("EVENT1",event.getAction()+"");
            if (event.getAction() == 1) {
                EditText editText = (EditText) v;
                SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();

                String valueS = editText.getText().toString();
                try {
                    int value = Integer.parseInt(valueS);
                    String key = "";
                    switch (editText.getId()) {
                        case R.id.editText_ip1: {
                            key = PreferenceSocketInfo.SERVER_IP_1;
                            break;
                        }
                        case R.id.editText_ip2: {
                            key = PreferenceSocketInfo.SERVER_IP_2;
                            break;
                        }
                        case R.id.editText_ip3: {
                            key = PreferenceSocketInfo.SERVER_IP_3;
                            break;
                        }
                        case R.id.editText_ip4: {
                            key = PreferenceSocketInfo.SERVER_IP_4;
                            break;
                        }
                        case R.id.editText_port: {
                            key = PreferenceSocketInfo.SERVER_PORT;
                            break;
                        }
                        default:
                            break;
                    }
                    editor.putInt(key, value);
                    editor.commit();

                } catch (NumberFormatException ee) {

                }
            }
            return false;
        }
    };

    View.OnClickListener btn_click_listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()){
                case R.id.cmd_send_btn:{
                    String msg = cmd_msg_text.getText().toString();
                    byte[] sendBytes = HexStrUtil.hexStr2Bytes(msg);
                    IoBuffer ioBuffer = IoBuffer.allocate(0).setAutoExpand(true);
                    ioBuffer.put(sendBytes).flip();

                    if(MinaClientThread.session != null){
                        MinaClientThread.session.write(ioBuffer);
                    }else {
                        Toast.makeText(getApplicationContext(),"连接异常！",Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case R.id.btn_connect:{
                    if(btn_connect.isChecked()){
                        Toast.makeText(getApplicationContext(),"将要连接",Toast.LENGTH_SHORT).show();
                        SharedPreferences.Editor editor = PreferenceCommon.sPreferences.edit();
                        editor.putInt(PreferenceSocketInfo.SERVER_IP_1,Integer.parseInt(editText_ip_01.getText().toString()));
                        editor.putInt(PreferenceSocketInfo.SERVER_IP_2,Integer.parseInt(editText_ip_02.getText().toString()));
                        editor.putInt(PreferenceSocketInfo.SERVER_IP_3,Integer.parseInt(editText_ip_03.getText().toString()));
                        editor.putInt(PreferenceSocketInfo.SERVER_IP_4,Integer.parseInt(editText_ip_04.getText().toString()));
                        editor.putInt(PreferenceSocketInfo.SERVER_PORT,Integer.parseInt(editText_port.getText().toString()));
                        editor.commit();
                        btn_connect.setEnabled(false);
                        if(MinaClientThread.session == null || MinaClientThread.session.isClosing()){
                            if(MinaClientThread.isCommplete){
                                new Thread(new MinaClientThread()).start();
                            }
                        }
                        autoConnected = true;
                    }else {
                        btn_connect.setEnabled(true);
                        Toast.makeText(getApplicationContext(),"将要断开",Toast.LENGTH_SHORT).show();
                        MinaClientThread.disConnect();
                        autoConnected = false;
                    }
                    break;
                }
                default:{
                    break;
                }
            }
        }
    };
}
